
package com.kxq.zhuoyue.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxq.zhuoyue.mapper.ClientGroupMapper;
import com.kxq.zhuoyue.mapper.ClientMapper;
import com.kxq.zhuoyue.po.ClientGroup;
import com.kxq.zhuoyue.po.Clients;
import com.kxq.zhuoyue.po.company.ScrmCompanyConfig;
import com.kxq.zhuoyue.service.ClientGroupService;
import com.kxq.zhuoyue.service.ClientService;
import com.kxq.zhuoyue.util.PublicWeChat;
import com.kxq.zhuoyue.util.WeChatUtil;
import com.kxq.zhuoyue.util.wechat.AccessToken;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ClientGroupServiceImpl extends ServiceImpl<ClientGroupMapper, ClientGroup> implements ClientGroupService {


    //获取当前用户的所有群聊列表信息
    public List<com.kxq.zhuoyue.po.ClientGroup> getChatGroupList(String clientGroupId) {
        //从对象中提取凭证
        String corpsecret="KGmpwdvAm2m_XgIDYsKtd8ViBGHDZ2QRXysG77fVydA";
        AccessToken accessToken = WeChatUtil.getAccessToken(corpsecret);
        String ACCESS_TOKEN = accessToken.getAccess_token();
        System.out.println(ACCESS_TOKEN);
        //拼接企业微信接口调用地址  拼接对应参数
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" + ACCESS_TOKEN;
        String result = "";
        List<ClientGroup> chatList=new ArrayList<>();
        try {
            URL postUrl = new URL(url);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();

            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            result = new String(jsonBytes, "UTF-8");
            Map<String,Object> map = JSON.parseObject(result, Map.class);
            List<Map<String, String>> chat_list = (List<Map<String, String>>) map.get("group_chat_list");

            /*for (Map<String, String> item : chat_list) {
                //chatList.add(getGroupMessage(item.get("chat_id"),companyId));
                chatList.add(getGroupMessage(item.get("chat_id"),companyId));
            }*/

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return chatList;
    }

    //调用企业微信接口，获取群消息
    public com.kxq.zhuoyue.po.ClientGroup getGroupMessage(String chatId, String companyId){

        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=";

        //封装发送消息请求JSON
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{");
        stringBuffer.append("\"chat_id\":" + "\"" + chatId + "\",");
        stringBuffer.append("\"need_name\": 1 ");
        stringBuffer.append("}");
        String json = stringBuffer.toString();
        String result = "";
        com.kxq.zhuoyue.po.ClientGroup group = new com.kxq.zhuoyue.po.ClientGroup();
        ScrmCompanyConfig scrmCompanyConfig = new ScrmCompanyConfig();
        scrmCompanyConfig.setCompanyId(companyId);
        //scrmCompanyConfig = companyService.getCompanyConfig(scrmCompanyConfig);
        String orgId = scrmCompanyConfig.getScrmOrgId();
        String orgNum = scrmCompanyConfig.getScrmOrgNum();
        try {
            PublicWeChat pub = new PublicWeChat();
            Map<String,Object> map = pub.pubWeChatUtil(url,json,companyId);
            Map<String, Object> group_chat = (Map<String, Object>) map.get("group_chat");
            group.setClientGroupId((String) group_chat.get("chat_id"));
            group.setClientGroupName((String) group_chat.get("name"));

            group.setEmpId((String) group_chat.get("owner"));
            int createTime = (Integer)group_chat.get("create_time");
            long millions=new Long(createTime).longValue()*1000;
            Calendar c=Calendar.getInstance();
            c.setTimeInMillis(millions);
            System.out.println(""+c.getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(c.getTime());
            group.setCreateTime(sdf.parse(dateString));

            List<Map<String, Object>> chat_users_list = (List<Map<String, Object>>) group_chat.get("member_list");
            long current=System.currentTimeMillis();//当前时间毫秒数
            long zero=current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
            long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
            int a=0;
            for (Map<String,Object> userListMap:chat_users_list){
                int joinTime=(Integer) userListMap.get("join_time");
                long join_time = joinTime*1000;
                if (join_time<twelve && join_time>=zero){
                    a++;
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return group;
    }
    //获取会话内容存档内部群信息
    public List<ClientGroup> insGroup() {
        //从对象中提取凭证
        String corpsecret="KGmpwdvAm2m_XgIDYsKtd8ViBGHDZ2QRXysG77fVydA";
        AccessToken accessToken = WeChatUtil.getAccessToken(corpsecret);
        String ACCESS_TOKEN = accessToken.getAccess_token();
        System.out.println(ACCESS_TOKEN);
        //拼接企业微信接口调用地址  拼接对应参数
        String url = "https://qyapi.weixin.qq.com/cgi-bin/msgaudit/groupchat/get?access_token=" + ACCESS_TOKEN;
        String result = "";
        List<ClientGroup> chatList=new ArrayList<>();
        try {
            URL postUrl = new URL(url);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();

            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            result = new String(jsonBytes, "UTF-8");
            Map<String,Object> map = JSON.parseObject(result, Map.class);
            List<Map<String, String>> chat_list = (List<Map<String, String>>) map.get("group_chat_list");

            /*for (Map<String, String> item : chat_list) {
                //chatList.add(getGroupMessage(item.get("chat_id"),companyId));
                chatList.add(getGroupMessage(item.get("chat_id"),companyId));
            }*/

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return chatList;
    }

}

